<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Cache;

class ProductCategory extends Model
{
    protected $guarded = [];

    public function children()
    {
        return $this->hasMany('App\Models\Shop\ProductCategory', 'parent_id', 'id');
    }

    /**
     * 筛选分类时,屏蔽掉没有商品的分类
     */
    static function filter_categories()
    {
        $categories = self::has('children.products')->with(['children' => function ($query) {
            $query->has('products');
        }])->get();
        return $categories;
    }

    //清除缓存
    static function clear()
    {
        Cache::forget('Shop123_category_categories');
    }

    /**
     * 生成分类数据
     * @return mixed
     */
    static function get_categories()
    {
        $categories = Cache::rememberForever('Shop123_category_categories', function () {
            return self::with(['children' => function ($query) {
                $query->orderBy('sort_order');
            }])->where('parent_id', 0)->orderBy('sort_order')->get();
        });
        Cache::forget('Shop123_category_categories');
        return $categories;
    }



}
